﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using UnityMultiPlayerGameServer.Data;
using GameProtocol;

namespace UnityMultiPlayerGameServer.Manager
{
    internal class DataBaseController
    {

        private string connectionString = "data source=localhost;" +
                                 "database=gameserver;" +
                                 "user id=root;" +
                                 "password=root;" +
                                 "pooling=true;";
        
        // 定义一个标识确保线程同步
        private static readonly object locker = new object();

        private static DataBaseController instance;
        public static DataBaseController Instance
        {
            get
            {
                if(instance == null)
                {
                    lock(locker)
                    {
                        if(instance == null)
                        {
                            instance = new DataBaseController();
                        }
                    }
                    
                }
                return instance;
            }
        }
        private DataBaseController(){}


        /// <summary>
        /// 用于在Program中开启一个实例，无实际内容
        /// </summary>
        public void start()
        {

        }

        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <returns></returns>
        private bool ConnectDatabase(MySqlConnection connection)
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("连接数据库时出错：\n" + e.Message);
                return false;
            }
        }

        /// <summary>
        /// 插入一条数据到数据库
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public UserInfo InsertData(string username, string password)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            if (!ConnectDatabase(connection))
            {
                return null;
            }
            try
            {          
                string sqlCommandStr = "INSERT INTO `gameserver`.`account` (`username`, `password`) VALUES ('" + username + "', '" + password + "')";
                Console.WriteLine(sqlCommandStr);
                MySqlCommand command = new MySqlCommand(sqlCommandStr,connection);
                int ret = (int)command.ExecuteNonQuery();
                Console.WriteLine(ret);
                if (ret >0)
                {
                    Console.WriteLine("插入用户成功");
                    connection.Close();
                    return GetUserDataFBase(username);
                }
                else
                {
                    Console.WriteLine("插入用户失败");
                    connection.Close();
                    return null;
                }
                
            }
            catch (Exception e)
            {
                connection.Close();
                Console.WriteLine("插入时出错：\n" + e.Message);
                return null;
            }
            
        }

        /// <summary>
        /// 查询数据库是否包含username
        /// </summary>
        /// <param name="username"></param>
        /// <param name="exceptionFlag">是否存在异常，true为存在</param>
        /// <returns>bool</returns>
        public bool TryFindUser(string username, out bool exceptionFlag)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            if (!ConnectDatabase(connection))
            {
                exceptionFlag = true;
                connection.Close();
                return false;
            }
            string sqlCommandStr = "select * from gameserver.account where username = '" + username + "';";
            Console.WriteLine(sqlCommandStr);
            try
            {
                MySqlCommand command = new MySqlCommand(sqlCommandStr, connection);
                MySqlDataReader reader = command.ExecuteReader();
                //Console.WriteLine("寻找" + username + "结果：" + reader.Read());
                exceptionFlag = false;
                bool ret = reader.Read();
                Console.WriteLine(ret ? "用户已存在" : "用户不存在");
                connection.Close();
                return ret;
            }
            catch (Exception e)
            {
                exceptionFlag = true;
                Console.WriteLine("查找用户数据存在时异常：\n" + e.Message);
                connection.Close();
                return false;
            }                    
        }

        /// <summary>
        /// 从数据库查找username信息
        /// </summary>
        /// <param name="flag">标识错误原因</param>
        /// <returns>UerData</returns>
        public UserInfo GetUserDataFBase(string username)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            if (!ConnectDatabase(connection))
            {
                connection.Close();
                return null;
            }
            try
            {
                string sqlCommandStr = "select * from gameserver.account where username = '" + username + "';";
                Console.WriteLine(sqlCommandStr);
                MySqlCommand command = new MySqlCommand(sqlCommandStr, connection);
                MySqlDataReader reader = command.ExecuteReader();
                if(! reader.Read())
                {
                    Console.WriteLine("没有在数据库中查询到 " + username);
                    return null;
                }

                //ReadSingleRow(reader);
                System.Data.IDataRecord dataRecord = reader;
                UserInfo data = new UserInfo();
                data.AccountID = dataRecord[0].ToString();
                data.UserName = dataRecord[1].ToString();
                data.Password = dataRecord[2].ToString();
                connection.Close();
                return data;
            }
            catch (Exception e)
            {
                Console.WriteLine("查找用户数据时异常：\n" + e.Message);
                connection.Close();
                return null;
            }
            
        }

        /// <summary>
        /// 输出从数据库查找的信息
        /// </summary>
        /// <param name="dataRecord"></param>
        private void ReadSingleRow(System.Data.IDataRecord dataRecord)
        {
            Console.WriteLine(String.Format("{0}, {1}, {2}", dataRecord[0], dataRecord[1], dataRecord[2]));
        }
    }
}
